<template>
  <div>
    <input type="text" v-model="title" @keydown.enter="addTodoList" v-focus />
    <button @click="clear">清理</button>
    <ul v-if="todolist.length > 0">
      <li v-for="(item, index) in todolist" :key="index">
        <input type="checkbox" v-model="item.done" />
        <span :class="{ done: item.done }">{{ item.title }}</span>
      </li>
    </ul>
    <div v-else>暂无数据...</div>
    <div>
      全选<input type="checkbox" v-model="alldone" />
      <span>{{ active }} / {{ all }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watchEffect, reactive } from "vue";

let { title, todolist ,addTodoList, clear, active, all, alldone } = userTodo()

let obj = reactive({
    count:1
})

let double = computed(()=> obj.count*2)

watchEffect(()=>{
    console.log('数据被修改了',obj.count,double.value)
})





function userTodo() {
  let title = ref("");
  let todolist = ref([{ title: "学习Vue", done: false }]);

  // 添加数据
  function addTodoList() {
    if (title.value === "") {
      console.log("请填写内容");
      return false;
    }
    try {
      todolist.value.forEach((item) => {
        if (item.title === title.value) {
          throw Error();
        }
      });
      todolist.value.push({
        title: title.value,
        done: false,
      });
      title.value = "";
    } catch {
      console.log("重复添加");
    }
  }

  // 删除数据

  function clear() {
    console.log(todolist);
    todolist.value = todolist.value.filter((v) => !v.done);
    console.log(todolist);
  }

  let active = computed(() => {
    return todolist.value.filter((v, index) => v.done).length;
  });
  let all = computed(() => todolist.value.length);

  let alldone = computed({
    get: function () {
      return active.value !== 0;
    },
    set: function (value) {
      todolist.value.forEach((item) => {
        item.done = value;
      });
    },
  });
  return {title, todolist,addTodoList, clear, active, all, alldone}
}
</script>

<style>
ul {
  padding: 0;
  margin: 10px 0;
}
li {
  text-align: left;
  list-style: none;
}
.done {
  color: red;
}
</style>